const express = require("express");
const router = express.Router();
const path = require("path");
const pool = require("../pool.js");
const utils = require("../utils/index.js");
const utilsServer = require("../utils/serverInfo.js");
const moment = require("moment-timezone");
const multer = require("multer");
const AdmZip = require("adm-zip");
const AppInfoParser = require("app-info-parser");
const plist = require("plist");
const fs = require("fs");
const { readManifest } = require("node-aab-parser");
const msgUtils = require("../utils/feishu.js");
const crypto = require("crypto");
const CryptoJS = require("crypto-js");
const FormData = require("form-data");
const { exec } = require("child_process");
const config = require("../config.js");
const androidPublisherConn = require("../google/googleapisAichat.js"); // './publisher' 是该文件的路径 
const axios = require("axios");

// 配置 multer 的存储设置
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 设置文件上传目录
        cb(null, "/home/wwwroot/default/images");
    },
    filename: function (req, file, cb) {
        // 生成文件名
        cb(null, Date.now() + "-" + file.originalname);
    },
});

const upload = multer({ storage: storage });

// 创建文件上传的 POST 接口
router.post("/upload", upload.single("file"), (req, res) => {
    const file = req.file;
    const { packageName } = req.body;
    if (!file) {
        return res.status(400).send("请上传一个文件。");
    }
    let fileUrl = ''

    fileUrl = `http://139.177.190.31/images/${file.filename}`;


    // 返回文件存储地址
    res.send({
        code: 0,
        message: "success",
        fileUrl: fileUrl,
    });
});

router.post('/reactivateSubscription', async (req, res) => {
    const { pk, orderId, uuid, email, images } = req.body;
    const missingParams = [];
    if (!pk) missingParams.push('pk');
    if (!orderId) missingParams.push('orderId');
    if (!uuid) missingParams.push('uuid');
    if (!email) missingParams.push('email');
    // if (!images) missingParams.push('images');

    // 如果有缺少的参数，返回错误信息
    if (missingParams.length > 0) {
        return res.status(400).json({ error: `Missing required parameters: ${missingParams.join(', ')}` });
    }
    let productId = null
    // 先去根据order查 有没有对应的productId,没有就null

    // 在 oneTime_product_notification 表中查找
    let sql = 'SELECT subscriptionId FROM oneTime_product_notification WHERE orderId = ?';
    let result = await mysqlQuery(sql, [orderId]);

    if (result.length > 0) {
        productId = result[0].subscriptionId;
    } else {
        // 如果没找到，再在 subscription_notification 表中查找
        sql = 'SELECT subscriptionId FROM subscription_notification WHERE latestOrderId = ?';
        result = await mysqlQuery(sql, [orderId]);

        if (result.length > 0) {
            productId = result[0].subscriptionId;
        }
    }

    const content = {
        id: utils.createId(),
        pk,
        orderId,
        uuid,
        email,
        images,
        productId,
        create_date: utils.formatDate(new Date()),
        update_date: utils.formatDate(new Date())
    };

    try {
        // 检查同一个 orderId 和 uuid 的记录是否已经存在
        const sqlCheck = 'SELECT * FROM subscription_recovery_requests WHERE orderId = ? AND uuid = ? AND status =0';
        const existingRecord = await mysqlQuery(sqlCheck, [orderId, uuid]);

        if (existingRecord.length > 0) {
            return res.send({
                code: 1,
                msg: "Already submitted an application"
            });
        }

        // 查询数据库，检查同一个 orderId 的不同 uuid 数量
        const sqlSelect = 'SELECT DISTINCT uuid FROM subscription_recovery_requests WHERE orderId = ? AND status = 0';
        const existingRecords = await mysqlQuery(sqlSelect, [orderId]);

        if (existingRecords.length >= 6) {
            return res.send({
                code: 1,
                msg: "The request to reactivate devices has reached the limit."
            });
        }

        // 插入新的记录
        const sqlInsert = 'INSERT INTO subscription_recovery_requests (id, pk, orderId, uuid, email, images,productId, create_date, update_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?,?)';

        await mysqlQuery(sqlInsert, [
            content.id,
            content.pk,
            content.orderId,
            content.uuid,
            content.email,
            content.images,
            content.productId,
            content.create_date,
            content.update_date
        ]);

        return res.send({
            code: 0,
            msg: "Reinstatement request submitted"
        });
    } catch (error) {
        console.log(error)
        res.status(500).json({ error: 'Internal server error' });
    }
});



router.post('/restoreUserSubscriptionStatus', async (req, res) => {
    let { id, token, state, productId, reason } = req.body;
    if (state == '1') {
        reason = null
    } else {
        token = null
    }

    try {
        // 查询数据库，检查记录是否存在
        const sqlSelect = 'SELECT * FROM subscription_recovery_requests WHERE id = ?';
        const existingRecord = await mysqlQuery(sqlSelect, [id]);

        if (existingRecord.length === 0) {
            return res.status(404).json({ error: 'Record not found' });
        }

        // 更新记录
        const sqlUpdate = `
            UPDATE subscription_recovery_requests 
            SET token = ?, state = ?, reason = ?,productId = ?, update_date = ?
            WHERE id = ?
        `;
        const updateDate = utils.formatDate(new Date());

        await mysqlQuery(sqlUpdate, [token, state, reason, productId, updateDate, id]);

        return res.status(200).json({ message: 'Record updated successfully' });
    } catch (error) {
        res.status(500).json({ error: 'Internal server error' });
    }
});

router.post("/test", async (req, res) => {
    console.log('---------test');
    res.send({ code: 0, msg: '接口部署成功-31' })

});
router.post('/checkSubscriptionStatus', async (req, res) => {
    const { orderId, uuid, pk } = req.body;
    if (!orderId || !uuid || !pk) {
        return res.send({
            code: 1,
            msg: "Missing required parameters"
        });

    }

    try {
        // 查询数据库，获取订阅状态
        const sqlSelect = 'SELECT * FROM subscription_recovery_requests WHERE orderId = ? AND uuid = ? AND pk = ? AND status = 0';
        const result = await mysqlQuery(sqlSelect, [orderId, uuid, pk]);

        if (result.length === 0) {
            return res.send({
                code: 2,
                msg: "Record not found"
            });

        }

        // 返回查询结果
        return res.send({
            code: 0,
            data: result[0],
            msg: "success"
        });
    } catch (error) {
        res.send({
            code: 500,
            msg: "Internal server error"
        });
    }
});

//申请记录列表
router.post("/getApplicationList", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    let { orderId, dateRange } = req.body;
    let sqlConditions = ["state = 0", "status = 0"]; // 添加 state = 0 条件
    const sqlParams = [];

    if (orderId) {
        sqlConditions.push("orderId = ?");
        sqlParams.push(orderId);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        sqlConditions.push("update_date BETWEEN ? AND ?");
        sqlParams.push(dateRange.start, dateRange.end);
    }

    let sqlBase = `SELECT * FROM subscription_recovery_requests`;
    let totalBase = "FROM subscription_recovery_requests";

    if (sqlConditions.length > 0) {
        sqlBase += ` WHERE ${sqlConditions.join(" AND ")}`;
        totalBase += ` WHERE ${sqlConditions.join(" AND ")}`;
    }

    let sqlCount = `SELECT COUNT(*) AS total_count ${totalBase}`;

    let { total } = await utils.getListSum(sqlCount, sqlParams, res, req);

    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";
    sqlParams.push(size, page);

    await pool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        result.forEach((element) => {
            element.package_name = element.pk;
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
        });
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});

router.post("/getOutcomeRecordList", async (req, res) => {
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    let { state, dateRange } = req.body;
    let sqlConditions = ["state != 0", "status = 0"]; // 添加 state = 0 条件
    const sqlParams = [];

    if (state) {
        sqlConditions.push("state = ?");
        sqlParams.push(state);
    }
    if (dateRange && dateRange.start && dateRange.end) {
        sqlConditions.push("update_date BETWEEN ? AND ?");
        sqlParams.push(dateRange.start, dateRange.end);
    }

    let sqlBase = `SELECT * FROM subscription_recovery_requests`;
    let totalBase = "FROM subscription_recovery_requests";

    if (sqlConditions.length > 0) {
        sqlBase += ` WHERE ${sqlConditions.join(" AND ")}`;
        totalBase += ` WHERE ${sqlConditions.join(" AND ")}`;
    }

    let sqlCount = `SELECT COUNT(*) AS total_count ${totalBase}`;

    let { total } = await utils.getListSum(sqlCount, sqlParams, res, req);

    sqlBase += " ORDER BY update_date DESC LIMIT ? OFFSET ?";
    sqlParams.push(size, page);

    await pool.query(sqlBase, sqlParams, (err, result) => {
        if (err) return res.send(utils.returnData({ code: -1, err, req }));
        result.forEach((element) => {
            element.package_name = element.pk;
            element.create_date = moment(element.create_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
            element.update_date = moment(element.update_date)
                .tz("Asia/Shanghai")
                .format("YYYY-MM-DD HH:mm:ss");
        });
        res.send(
            utils.returnData({
                data: result,
                total: total,
            })
        );
    });
});
router.post("/deleteHandel", async (req, res) => {
    let { id } = req.body;
    const sql = `UPDATE subscription_recovery_requests SET status = 1 WHERE id = ?`;
    let result = await mysqlQuery(sql, [id])
    res.send(
        {
            code: 0,
            msg: 'success'
        }
    );
});

//获取项目列表
router.post('/extractPackageNamesSubscription', async (req, res) => {
    let sql = `SELECT DISTINCT packageName FROM subscription_notification;`
    let result = await mysqlQuery(sql)
    if (result.length != 0) {
        result.forEach(item => {
            item.package_name = item.packageName
        })
    }
    res.send(
        utils.returnData({
            data: utils.mapPackageNamesToShortNames(result)
        })
    );
});
router.post('/extractPackageNamesVoidedPurchase', async (req, res) => {
    let sql = `SELECT DISTINCT packageName FROM voided_purchase_notification;`
    let result = await mysqlQuery(sql)
    if (result.length != 0) {
        result.forEach(item => {
            item.package_name = item.packageName
        })
    }
    res.send(
        utils.returnData({
            data: utils.mapPackageNamesToShortNames(result)
        })
    );
});

router.post('/extractPackageNamesOneTimeProduct', async (req, res) => {
    let sql = `SELECT DISTINCT packageName FROM oneTime_product_notification;`
    let result = await mysqlQuery(sql)
    if (result.length != 0) {
        result.forEach(item => {
            item.package_name = item.packageName
        })
    }
    res.send(
        utils.returnData({
            data: utils.mapPackageNamesToShortNames(result)
        })
    );
});

//一次性 列表
router.post('/getOneTimeProductList', async (req, res) => {
    const { pk, dateRange, orderId, notificationType, acknowledgementState, regionCode } = req.body;
    let { page, size } = utils.pageSize(req.body.page, req.body.size);

    // 基础的 SQL 查询
    let sql = `FROM oneTime_product_notification WHERE packageName = ?`;
    let params = [pk];
    if (orderId) {
        sql += ` AND orderId = ?`;
        params.push(orderId);
    }
    if (notificationType) {
        sql += ` AND notificationType = ?`;
        params.push(notificationType);
    }
    if (acknowledgementState) {
        sql += ` AND acknowledgementState = ?`;
        params.push(acknowledgementState);
    }
    if (regionCode) {
        sql += ` AND regionCode = ?`;
        params.push(regionCode);
    }
    if (dateRange && dateRange.start && dateRange.end) {

        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` AND update_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    // 统计总条数的 SQL
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;

    // 查询数据的 SQL
    let sqlSelect = `SELECT * ${sql} ORDER BY update_date DESC`;

    try {
        let { total } = await utils.getListSum(sqlCount, params, res, req);

        // 查询数据
        sqlSelect += ` LIMIT ? OFFSET ?`;
        params.push(size, page);

        await pool.query(sqlSelect, params, async (err, result) => {
            if (err) return res.send(utils.returnData({ code: -1, err, req }));

            // 处理日期格式
            result.forEach((element) => {
                element.create_date = moment(element.create_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
                element.update_date = moment(element.update_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
            });

            // 返回数据
            res.send(
                utils.returnData({
                    data: result,
                    total: total,
                })
            );
        });
    } catch (err) {
        res.send(utils.returnData({ code: -1, err, req }));
    }
})


//作废 列表
router.post('/getVoidedPurchaseList', async (req, res) => {
    const { pk, dateRange, orderId, productType, acknowledgementState, regionCode } = req.body;
    let { page, size } = utils.pageSize(req.body.page, req.body.size);
    // 基础的 SQL 查询
    let sql = `FROM voided_purchase_notification WHERE packageName = ?`;
    let params = [pk];
    if (orderId) {
        sql += ` AND orderId = ?`;
        params.push(orderId);
    }
    if (productType) {
        sql += ` AND productType = ?`;
        params.push(productType);
    }
    if (acknowledgementState) {
        sql += ` AND acknowledgementState = ?`;
        params.push(acknowledgementState);
    }
    if (regionCode) {
        sql += ` AND regionCode = ?`;
        params.push(regionCode);
    }
    if (dateRange && dateRange.start && dateRange.end) {

        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` AND update_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    // 统计总条数的 SQL
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;

    // 查询数据的 SQL
    let sqlSelect = `SELECT * ${sql} ORDER BY update_date DESC`;

    try {
        let { total } = await utils.getListSum(sqlCount, params, res, req);

        // 查询数据
        sqlSelect += ` LIMIT ? OFFSET ?`;
        params.push(size, page);
        await pool.query(sqlSelect, params, async (err, result) => {
            if (err) return res.send(utils.returnData({ code: -1, err, req }));

            // 处理日期格式
            result.forEach((element) => {
                element.create_date = moment(element.create_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
                element.update_date = moment(element.update_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
            });

            // 返回数据
            res.send(
                utils.returnData({
                    data: result,
                    total: total,
                })
            );
        });
    } catch (err) {
        res.send(utils.returnData({ code: -1, err, req }));
    }
})

//订阅 列表
router.post('/getSubscriptionList', async (req, res) => {
    const { pk, dateRange, orderId, notificationType, acknowledgementState, regionCode } = req.body;
    let { page, size } = utils.pageSize(req.body.page, req.body.size);

    // 基础的 SQL 查询
    let sql = `FROM subscription_notification WHERE packageName = ?`;
    let params = [pk];
    if (orderId) {
        sql += ` AND latestOrderId = ?`;
        params.push(orderId);
    }
    if (notificationType) {
        sql += ` AND notificationType = ?`;
        params.push(notificationType);
    }
    if (acknowledgementState) {
        sql += ` AND acknowledgementState = ?`;
        params.push(acknowledgementState);
    }
    if (regionCode) {
        sql += ` AND regionCode = ?`;
        params.push(regionCode);
    }
    if (dateRange && dateRange.start && dateRange.end) {

        const startDate = moment(dateRange.start).startOf('day').format('YYYY-MM-DD HH:mm:ss');
        const endDate = moment(dateRange.end).endOf('day').format('YYYY-MM-DD HH:mm:ss');
        sql += ` AND update_date BETWEEN ? AND ?`;
        params.push(startDate, endDate);
    }

    // 统计总条数的 SQL
    let sqlCount = `SELECT COUNT(*) AS total_count ${sql}`;

    // 查询数据的 SQL
    let sqlSelect = `SELECT * ${sql} ORDER BY update_date DESC`;

    try {
        let { total } = await utils.getListSum(sqlCount, params, res, req);

        // 查询数据
        sqlSelect += ` LIMIT ? OFFSET ?`;
        params.push(size, page);

        await pool.query(sqlSelect, params, async (err, result) => {
            if (err) return res.send(utils.returnData({ code: -1, err, req }));

            // 处理日期格式
            result.forEach((element) => {
                element.create_date = moment(element.create_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
                element.update_date = moment(element.update_date)
                    .tz("Asia/Shanghai")
                    .format("YYYY-MM-DD HH:mm:ss");
            });

            // 返回数据
            res.send(
                utils.returnData({
                    data: result,
                    total: total,
                })
            );
        });
    } catch (err) {
        res.send(utils.returnData({ code: -1, err, req }));
    }
})

router.post('/google-notifications', async (req, res) => {
    const chinaTime = new Date();
    const { message } = req.body;
    const { data } = message;
    const decodedData = Buffer.from(data, 'base64').toString('utf-8');
    const notification = JSON.parse(decodedData);


    req.body.message.data = notification;

    let content = {}
    content.messageId = req.body.message.messageId
    content.packageName = notification.packageName
    content.eventTimeMillis = notification.eventTimeMillis

    let type = ''

    if (notification.testNotification) return
    console.log(JSON.stringify(notification), 'JSON.stringify(notification)')

    async function isMessageIdExists(tableName, messageId) {
        const query = `SELECT 1 FROM ${tableName} WHERE messageId = ? LIMIT 1`;
        const result = await utils.query(query, [messageId]);
        return result.length > 0;
    }
    if (notification.subscriptionNotification) {  // 通知与订阅相关
        type = "subscriptionNotification"
        let notificationType = notification.subscriptionNotification.notificationType
        // if (notificationType != '2' && notificationType != '4') return
        content.notificationType = notification.subscriptionNotification.notificationType
        content.purchaseToken = notification.subscriptionNotification.purchaseToken
        content.subscriptionId = notification.subscriptionNotification.subscriptionId
        // 检查 messageId 是否已存在
        if (await isMessageIdExists('subscription_notification', content.messageId)) return;
    }
    if (notification.oneTimeProductNotification) { // 一次性购买相关
        type = "oneTimeProductNotification"
        content.purchaseToken = notification.oneTimeProductNotification.purchaseToken
        content.subscriptionId = notification.oneTimeProductNotification.sku
        content.notificationType = notification.oneTimeProductNotification.notificationType
        // 检查 messageId 是否已存在
        if (await isMessageIdExists('oneTime_product_notification', content.messageId)) return;
    }
    if (notification.voidedPurchaseNotification) { //通知与作废的购买交易相关
        type = "voidedPurchaseNotification"
        content.purchaseToken = notification.voidedPurchaseNotification.purchaseToken
        content.orderId = notification.voidedPurchaseNotification.orderId
        content.productType = notification.voidedPurchaseNotification.productType
        content.refundType = notification.voidedPurchaseNotification.refundType
        // 检查 messageId 是否已存在
        if (await isMessageIdExists('voided_purchase_notification', content.messageId)) return;
    }


    content.type = type

    let androidPublisher = await androidPublisherConn(content.packageName);
    try {
        let response = ''
        if (type == 'oneTimeProductNotification') {
            response = await androidPublisher.purchases.products.get({
                packageName: content.packageName,
                token: content.purchaseToken,
                productId: content.subscriptionId,
            });
            content.id = utils.createId();
            content.orderId = response.data.orderId || null
            content.purchaseTimeMillis = response.data.purchaseTimeMillis
            content.purchaseState = response.data.purchaseState
            content.consumptionState = response.data.consumptionState
            content.developerPayload = response.data.developerPayload
            content.acknowledgementState = response.data.acknowledgementState
            content.kind = response.data.kind
            content.regionCode = response.data.regionCode
            content.purchaseType = response.data.purchaseType
            content.refundableQuantity = response.data.refundableQuantity
            content.create_date = utils.formatDate(new Date());
            content.update_date = utils.formatDate(new Date());
            const { text, values } = utils.createInsertSql(
                "oneTime_product_notification",
                content
            );
            let result = await utils.query(text, values);
        } else if (type == 'voidedPurchaseNotification') {
            response = await androidPublisher.purchases.subscriptionsv2.get({
                packageName: content.packageName,
                token: content.purchaseToken,
            });
            let date = new Date(response.data.startTime);
            let mysqlDate = date.toISOString().slice(0, 19).replace('T', ' ');
            content.id = utils.createId();
            content.kind = response.data.kind
            content.startTime = mysqlDate
            content.regionCode = response.data.regionCode
            content.subscriptionState = response.data.subscriptionState
            content.latestOrderId = response.data.latestOrderId
            content.acknowledgementState = response.data.acknowledgementState
            content.lineItems = JSON.stringify(response.data.lineItems)
            content.canceledStateContext = JSON.stringify(response.data.canceledStateContext)
            content.create_date = utils.formatDate(new Date());
            content.update_date = utils.formatDate(new Date());
            const { text, values } = utils.createInsertSql(
                "voided_purchase_notification",
                content
            );
            let result = await utils.query(text, values);
        } else {
            response = await androidPublisher.purchases.subscriptionsv2.get({
                packageName: content.packageName,
                token: content.purchaseToken,
            });
            let date = new Date(response.data.startTime);
            let mysqlDate = date.toISOString().slice(0, 19).replace('T', ' ');
            content.id = utils.createId();
            content.kind = response.data.kind
            content.startTime = mysqlDate
            content.regionCode = response.data.regionCode
            content.subscriptionState = response.data.subscriptionState
            content.latestOrderId = response.data.latestOrderId
            content.acknowledgementState = response.data.acknowledgementState
            content.lineItems = JSON.stringify(response.data.lineItems)
            content.create_date = utils.formatDate(new Date());
            content.update_date = utils.formatDate(new Date());
            const { text, values } = utils.createInsertSql(
                "subscription_notification",
                content
            );
            let result = await utils.query(text, values);
        }
    } catch (error) {

        console.error('Error fetching subscription:', error);

    }

});

//获取国家列表
router.post("/getVoidedStorefrontList", async (req, res) => {
    const { pk } = req.body; // 从请求体中获取 pk

    const sql = `
        SELECT DISTINCT regionCode 
        FROM voided_purchase_notification
        WHERE packageName = ?;`; // 使用占位符来防止 SQL 注入

    try {
        // 获取去重后的 storefront 列表
        const result = await new Promise((resolve, reject) => {
            pool.query(sql, [pk], (err, results) => { // 传入 pk 参数
                if (err) return reject(err);
                resolve(results);
            });
        });

        // 数据处理，将结果转换成指定的格式
        const data = result.map((row, index) => ({
            id: index + 1,
            name: row.regionCode
        }));

        // 将结果发送给客户端
        res.send({
            code: 0,
            msg: "操作成功",
            data: data
        });

    } catch (err) {
        res.send({
            code: -1,
            msg: "操作失败",
            error: err.message
        });
    }
});


router.post("/getSubscriptionStorefrontList", async (req, res) => {
    const { pk } = req.body;
    const sql = `SELECT DISTINCT regionCode FROM subscription_notification WHERE packageName = ?;`;

    try {
        // 获取去重后的 storefront 列表
        const result = await new Promise((resolve, reject) => {
            pool.query(sql, [pk], (err, results) => { // 传入 pk 参数
                if (err) return reject(err);
                resolve(results);
            });
        });

        // 数据处理，将结果转换成指定的格式
        const data = result.map((row, index) => ({
            id: index + 1,
            name: row.regionCode
        }));

        // 将结果发送给客户端
        res.send({
            code: 0,
            msg: "操作成功",
            data: data
        });

    } catch (err) {
        res.send({
            code: -1,
            msg: "操作失败",
            error: err.message
        });
    }
});
router.post("/getOneTimeStorefrontList", async (req, res) => {
    const { pk } = req.body;
    const sql = `SELECT DISTINCT regionCode FROM oneTime_product_notification WHERE packageName = ?;`;

    try {
        // 获取去重后的 storefront 列表
        const result = await new Promise((resolve, reject) => {
            pool.query(sql, [pk], (err, results) => { // 传入 pk 参数
                if (err) return reject(err);
                resolve(results);
            });
        });

        // 数据处理，将结果转换成指定的格式
        const data = result.map((row, index) => ({
            id: index + 1,
            name: row.regionCode
        }));

        // 将结果发送给客户端
        res.send({
            code: 0,
            msg: "操作成功",
            data: data
        });

    } catch (err) {
        res.send({
            code: -1,
            msg: "操作失败",
            error: err.message
        });
    }
});

async function mysqlQuery(sql, arr) {

    return new Promise((resolve, reject) => {
        pool.query(sql, arr, (error, results, fields) => {
            if (error) {
                return reject(error);
            }
            resolve(results);
        });
    });
}
module.exports = router;

